package com.study.volatile_study;

public class Volatile1 {
    public volatile int inc = 0;
     
    public void increase() {
        inc++;
        System.out.println(Thread.currentThread().getName()+"||inc="+inc);
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Volatile1 test = new Volatile1();
        for(int i=0;i<10;i++){
            new Thread(){
                @Override
                public void run() {
                    for(int j=0;j<1000;j++){
                        test.increase();
                    }
                };
            }.start();
        }
        //保证前面的线程都执行完
        while (Thread.activeCount() > 2) {
            System.out.println("Thread.yield();"+Thread.activeCount());
//            Thread.sleep(1L);
            Thread.yield();
        }
        //多次执行inc<10000；说明线程不安全
        System.out.println(Thread.activeCount()+"||"+test.inc);
    }
}